package com.newtouch.bxzs.database.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.CooperationCompanyOrganization;
import com.newtouch.bxzs.common.base.model.OrganizationMap;
import com.newtouch.bxzs.common.base.util.PinYinUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.database.mapper.CooperationCompanyOrganizationMapper;
import com.newtouch.bxzs.database.mapper.OrganizationMapper;
import com.newtouch.bxzs.database.mapper.OrganizationMappingMapper;
import com.newtouch.bxzs.database.model.*;
import com.newtouch.bxzs.database.service.OrganizationMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;


/**
 * 映射机构关系查询实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2020/12/22 14:47</td>
 * <td>Amour</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author lhx
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class OrganizationMappingServiceImpl implements OrganizationMappingService {
    /*映射机构信息mapper*/
    @Autowired
    private OrganizationMappingMapper organizationMappingMapper;

    /*对端机构信息mapper*/
    @Autowired
    private CooperationCompanyOrganizationMapper cooperationCompanyOrganizationMapper;

    /*机构信息mapper*/
    @Autowired
    private OrganizationMapper organizationMapper;

    /**
     * 根据机构名称获取机构映射关系信息
     *com.newtouch.bxzs.database.service.OrganizationMappingService#getMappingList(
     * @param organizationVO 机构名称
     * @return IPage<OrganizationMapBO>
     */
    @Override
    public IPage<OrganizationMapBO> getMappingList(OrganizationVO organizationVO) {
        Page<OrganizationMapBO> mappingList = new Page<>(organizationVO.getCurrentPage(),
                organizationVO.getPageSize());
        if (StringUtils.isEmpty(organizationVO.getOrganizationName())) {
            /* 多表查询在Mapper用注解的形式使用SQL*/
            mappingList = organizationMappingMapper.organizationMappingBO(mappingList);
        } else {
            /* 多表查询在Mapper用注解的形式使用SQL*/
            mappingList = organizationMappingMapper.organizationMappingCondition("%" + organizationVO.getOrganizationName() + "%", mappingList);
        }
        return mappingList;
    }

    /**
     * 根据用户机构编码获取映射关系信息
     *com.newtouch.bxzs.database.service.OrganizationMappingService#getMappingListByCode
     * @param organizationMapByUserVO 用户机构编码
     * @return OrganizationMapTotalBO
     */
    @Override
    public OrganizationMapTotalBO getMappingListByCode(OrganizationMapByUserVO organizationMapByUserVO) {
        String userOrganizationCode = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserOrganizationCode();
        //查询本级机构所有上级机构ID
        String organizationSynList= organizationMapper.selecParentOrganizationCodeStr(userOrganizationCode);
        List<String> result = Arrays.asList(organizationSynList.split(","));
        /* 多表查询在Mapper用注解的形式使用SQL*/
        List<OrganizationMapByUserBO> mappingList = organizationMappingMapper.organizationMappingByCode(result,organizationMapByUserVO.getDataSource(), organizationMapByUserVO.getOrganizationName());
        HashMap<String, List<OrganizationMapByUserBO>> hashMap = new HashMap<>();
        // 判断是否需要首字母
        if (organizationMapByUserVO.getFirstFlag()) {
            //机构名称拼音首字母作为key
            for (OrganizationMapByUserBO orgBO : mappingList) {
                String organizationNameFullSpelling= orgBO.getCooperationCompanyOrganizationNameFullSpelling();
                //如果全拼为空，调拼音工具类，再次获取全拼
                if(StringUtils.isEmpty(organizationNameFullSpelling)){
                    String name = orgBO.getCooperationCompanyOrganizationName();
                    //名称为空则抛出异常
                    if(StringUtils.isEmpty(name)){
                        throw  new BaseException(BaseErrorEnum.NOT_FOUND);
                    }
                    organizationNameFullSpelling = PinYinUtils.toFirstChar(name);
                }
                String charFirst = organizationNameFullSpelling.charAt(0)+"";
                String first = charFirst.toUpperCase();
                List<OrganizationMapByUserBO> list = hashMap.get(first);
                if (CollectionUtil.isEmpty(list)) {
                    list = new ArrayList<>();
                }
                list.add(orgBO);
                hashMap.put(first, list);
            }
        } else {
            hashMap.put("mappingList", mappingList);
        }
        OrganizationMapTotalBO organizationMapTotalBO = new OrganizationMapTotalBO();
        //设置总条数
        organizationMapTotalBO.setTotal(mappingList.size());
        organizationMapTotalBO.setOrganizationMapTotalBOList(hashMap);
        return organizationMapTotalBO;
    }
    /**
     * 根据主键查看机构映射关系详情信息
     *com.newtouch.bxzs.database.service.OrganizationMappingService#getOrganizationMappingInfo
     * @param orgMappId 关系id
     * @return OrganizationMapBO
     */
    @Override
    public OrganizationMapBO getOrganizationMappingInfo(String orgMappId) {
        if(StringUtils.isEmpty(orgMappId)){
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        OrganizationMapBO organizationMapInfo=organizationMappingMapper.organizationMappingInfo(orgMappId);
        return organizationMapInfo;
    }

    /**
     * 新增机构映射关系信息
     * com.newtouch.bxzs.database.service.OrganizationMappingService#insertMapping
     * @param organizationMapModifyVO 新增内容
     * @return
     */
    @Override
    public int modifyMapping(OrganizationMapModifyVO organizationMapModifyVO) {
        if(StringUtils.isEmpty(organizationMapModifyVO.getCooperationCompanyOrganizationId())){
            throw new BaseException("-1","保险机构未选择");
        }
        if(StringUtils.isEmpty(organizationMapModifyVO.getOrganizationId())){
            throw new BaseException("-1","银行机构未选择");
        }
        OrganizationMap organizationMap = new OrganizationMap();
        BeanUtil.copyProperties(organizationMapModifyVO, organizationMap);
        // 获取当前登录用户
        organizationMap.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        organizationMap.setCreateTime(new Date());
        organizationMap.setEnableFlag(false);
        //校验该映射关系以及上级是否存在
        String organizationSynList= cooperationCompanyOrganizationMapper.modifyOrganizationMapping(organizationMapModifyVO.getCooperationCompanyOrganizationCode(), organizationMapModifyVO.getDataSource());
        List<String> result = Arrays.asList(organizationSynList.split(","));
        QueryWrapper<CooperationCompanyOrganization> queryInsurance = new QueryWrapper<>();
        queryInsurance.in("COOPERATION_COMPANY_ORGANIZATION_CODE",result);
        queryInsurance.eq("DATA_SOURCE", organizationMapModifyVO.getDataSource());
        List<CooperationCompanyOrganization> organizationInsurance= cooperationCompanyOrganizationMapper.selectList(queryInsurance);
        List<String> orgOppositeId = new ArrayList<String>();
        for (CooperationCompanyOrganization item:organizationInsurance) {
            orgOppositeId.add(item.getCooperationCompanyOrganizationId());
        }
        QueryWrapper<OrganizationMap> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("COOPERATION_COMPANY_ORGANIZATION_ID",orgOppositeId);
        queryWrapper.eq("ORGANIZATION_ID", organizationMapModifyVO.getOrganizationId());
        List<OrganizationMap> organizationMappingOne=organizationMappingMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(organizationMapModifyVO.getOrganizationMapId())) {
            if (!CollectionUtil.isEmpty(organizationMappingOne)){
                throw new BaseException("-1","该映射关系已存在或已存在与上级机构的映射关系");
            }
            /* 主键为空的时候，执行新增*/
            organizationMap.setCreateUserId(UserDetailUtil.getUserDetail().getUserId());
            organizationMap.setCreateTime(new Date());
            return organizationMappingMapper.insert(organizationMap);
        }else {
            if(!CollectionUtil.isEmpty(organizationMappingOne)){
                for(OrganizationMap item:organizationMappingOne){
                    if(item.getOrganizationMapId().equals(organizationMapModifyVO.getOrganizationMapId())){
                        return organizationMappingMapper.updateById(organizationMap);
                    }
                }
                throw new BaseException("-1","该映射关系已存在与对端上级机构的映射关系");
            }
            return organizationMappingMapper.updateById(organizationMap);
        }
    }



    /**
     * 根据主键设置机构映射关系信息为不可见
     * com.newtouch.bxzs.database.service.OrganizationMappingService#deleteMapping
     * @param organizationMappingIds 机构编码集合
     * @return
     */
    @Override
    public int deleteMapping(List<String> organizationMappingIds) {
        if (CollectionUtil.isEmpty(organizationMappingIds)) {
            //为空抛出异常信息
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        QueryWrapper<OrganizationMap> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("ORGANIZATION_MAP_ID", organizationMappingIds);
        queryWrapper.eq("IS_ENABLE", 1);
        List<OrganizationMap> organizationMappinList = organizationMappingMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(organizationMappinList)) {
            throw new BaseException("-1","不允许删除启用状态的映射关系");
        }
        //批量逻辑删除映射关系
        return organizationMappingMapper.deleteBatchIds(organizationMappingIds);
    }

    /**
     * 根据主键修改机构映射关系信息状态
     * com.newtouch.bxzs.database.service.OrganizationMappingService#modifyMappingState
     * @param organizationMapVO  修改内容
     * @return
     */
    @Override
    public int modifyMappingState(OrganizationMapVO organizationMapVO) {
        /*修改主键不为空的时候，且未被逻辑删除的映射机构状态*/
        if (StringUtils.isEmpty(organizationMapVO.getOrganizationMapId())) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        if (StringUtils.isEmpty(organizationMapVO.getEnableFlag())) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        OrganizationMap organizationMap = new OrganizationMap();
        organizationMap.setEnableFlag(organizationMapVO.getEnableFlag());
        organizationMap.setUpdateTime(new Date());
        //获取当前登录用户
        organizationMap.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        QueryWrapper<OrganizationMap> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORGANIZATION_MAP_ID", organizationMapVO.getOrganizationMapId());
        return organizationMappingMapper.update(organizationMap, queryWrapper);
    }


}
